import requests
import json
from pathlib import Path

def file_request_post(url, file_path):
    httpclient = requests.Session()
    res_dict = None
    try:
        with open(file_path, 'rb') as file:
            # 构建文件流
            files = {'file': (Path(file_path).name, file)}
            data = {'fileHost_': 'http://sm.valuemap.cn/file'}
            response = httpclient.post(url, files=files, data=data)

            # 处理响应
            response.raise_for_status()
            resp = response.text
            res_dict = json.loads(resp)

            if res_dict is not None:
                code = res_dict.get('code')
                if code!= 200:
                    return None

                return res_dict.get('url')
    except requests.exceptions.RequestException as e:
        raise Exception("操作失败：文件上传出错 " + str(e))

    return None

def upload_file(file_path):
    print("file_path 上传的文件为：", file_path)
    url = 'http://192.168.1.161:8080/common/upload/host/group2'  # 请替换为实际的上传 URL
    result = file_request_post(url, file_path)
    if result:
        print("上传成功，获取的 URL 为:", result)
        return str(result)  # 将 result 转换为字符串返回
    else:
        print("上传失败")
        return "上传失败"  # 返回指定的字符串表示上传失败